package com.mishow.activity;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import org.json.JSONObject;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

import com.alibaba.fastjson.JSON;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.core.PoiItem;
import com.android.volley.Request;
import com.mishow.R;
import com.mishow.activity.base.BaseActivity;
import com.mishow.activity.photo.AlbumActivity;
import com.mishow.activity.photo.GalleryActivity;
import com.mishow.adapter.photo.GridAdapter;
import com.mishow.bean.photo.ImageItem;
import com.mishow.log.MyLog;
import com.mishow.net.HttpUrlConstant;
import com.mishow.net.NetworkUtil;
import com.mishow.preferenses.SharedPreferencesUtil;
import com.mishow.request.core.Response;
import com.mishow.request.listener.OnResponseListener;
import com.mishow.request.response.UploadImageFileResponse;
import com.mishow.utils.AndroidUtil;
import com.mishow.utils.Constants;
import com.mishow.utils.FileUtil;
import com.mishow.utils.ToastUtil;
import com.mishow.utils.photo.Bimp;
import com.mishow.utils.photo.PublicWay;
import com.mishow.utils.photo.Res;
import com.mishow.volley.http.mine.MultipartRequestParams;
import com.mishow.volley.http.request.FastJsonRequest;
import com.mishow.volley.http.request.MultipartRequest;
import com.mishow.widget.UploadImageDialog;
import com.mishow.widget.UploadVideoDialog;

/**
 * 
 * 作者：wei.miao <br/>
 * 描述： 动态发布activity
 */
public class DynamicReleaseActivity extends BaseActivity {

	/** 取消 **/
	private TextView txt_dynamic_cancel;
	/** 发表 **/
	private TextView txt_dynamic_publish;
	/** 说点什么 **/
	private EditText edit_dynamic_desc;

	/** 添加照片 **/
	private ImageView image_photo;
	/** 添加视频 **/
	private ImageView image_video;
	/** 其它 **/
	private ImageView image_other;

	private TextView text_location;

	/** 所在位置 **/
	private RelativeLayout relative_dynamic_location;

	/**
	 * 上传图片对话框
	 **/
	private UploadImageDialog uploadImageDialog;
	/**
	 * 上传视频对话框
	 **/
	private UploadVideoDialog uploadVideoDialog;
	/**
	 * 拍照的图片文件
	 **/
	private File cameraFile;

	private String fileImagePath;

	private SharedPreferencesUtil mShPreferencesUtil;
	
	private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
	/** 发布动态时间 **/
	private String mInitEndTime;
	// -------------------------------------
	public static Bitmap bimap;
	/** 图片 **/
	private GridView noScrollgridview;

	private GridAdapter adapter;

	public static void intoActivity(Context context) {

		Intent intent = new Intent(context, DynamicReleaseActivity.class);
		context.startActivity(intent);

	}

	@Override
	protected void initData() {

		Res.init(this);
		bimap = BitmapFactory.decodeResource(getResources(),R.drawable.icon_dynarmic_select);
		PublicWay.activityList.add(this);

		mShPreferencesUtil = new SharedPreferencesUtil(mContext);
		//默认为当前时间 
		mInitEndTime = dateFormat.format(new Date());

	}

	@Override
	protected void initView(Bundle savedInstanceState) {

		setContentView(R.layout.activity_dynamicrelease);

		txt_dynamic_cancel = (TextView) findViewById(R.id.txt_dynamic_cancel);
		txt_dynamic_publish = (TextView) findViewById(R.id.txt_dynamic_publish);
		edit_dynamic_desc = (EditText) findViewById(R.id.edit_dynamic_desc);

		image_photo = (ImageView) findViewById(R.id.image_photo);
		image_video = (ImageView) findViewById(R.id.image_video);
		image_other = (ImageView) findViewById(R.id.image_other);

		text_location = (TextView) findViewById(R.id.text_location);

		relative_dynamic_location = (RelativeLayout) findViewById(R.id.relative_dynamic_location);

		noScrollgridview = (GridView) findViewById(R.id.noScrollgridview);
	}

	@Override
	protected void setAttribute() {

		txt_dynamic_cancel.setOnClickListener(onClickListener);
		txt_dynamic_publish.setOnClickListener(onClickListener);
		edit_dynamic_desc.setOnClickListener(onClickListener);
		image_photo.setOnClickListener(onClickListener);
		image_video.setOnClickListener(onClickListener);
		image_other.setOnClickListener(onClickListener);
		relative_dynamic_location.setOnClickListener(onClickListener);

		noScrollgridview.setSelector(new ColorDrawable(Color.TRANSPARENT));
		adapter = new GridAdapter(this);
		adapter.update();
		noScrollgridview.setAdapter(adapter);
		noScrollgridview.setOnItemClickListener(new OnItemClickListener() {

			public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
					long arg3) {
				if (arg2 == Bimp.tempSelectBitmap.size()) {
					MyLog.d("arg2==" + arg2);
					showUploadImageDialog();
				} else {
					Intent intent = new Intent(DynamicReleaseActivity.this,GalleryActivity.class);
					intent.putExtra("position", "3");
					intent.putExtra("ID", arg2);
					startActivity(intent);
				}
			}
		});

	}

	private OnClickListener onClickListener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			switch (v.getId()) {
			case R.id.txt_dynamic_cancel:
				onBack();
				break;
			case R.id.txt_dynamic_publish:
				if (edit_dynamic_desc.getText().toString().length() < 1) {

					ToastUtil.show(mContext, "说点什么吧");
				} else {
					// 请求服务端接口
					if (Bimp.tempSelectBitmap != null && Bimp.tempSelectBitmap.size() > 0) {
						
						doUploadImage(Bimp.tempSelectBitmap);
					}
				}
				break;
			case R.id.edit_dynamic_desc:

				break;
			case R.id.image_photo:
				showUploadImageDialog();
				break;
			case R.id.image_video:
				showUploadVideoDialog();
				break;
			case R.id.image_other:

				break;
			case R.id.relative_dynamic_location:
				DynamicLocationActivity.intoActivity(mContext);
				break;

			default:
				break;
			}

		}
	};
	
	
	/**
     *上传图片接口
     * @param orignalFilePath
     * @param uploadFile
     */
    private void doUploadImage(ArrayList<ImageItem> uploadFile) {

        if (!AndroidUtil.isNetworkAvailable(this)) { // 无网络连接
            ToastUtil.show(mContext, getString(R.string.no_connector));
            return;
        }
        showProgress("", "", false);
        MultipartRequestParams params = new MultipartRequestParams();
        for (int i = 0; i < uploadFile.size(); i++) {
			
        	String file = uploadFile.get(i).imagePath;
        	params.put("imgFile", new File(file));
		}
        
        String url = HttpUrlConstant.getPostUrl(this,HttpUrlConstant.SAVE_UPLOAD_IMG);
        
        OnResponseListener<JSONObject> listener = new OnResponseListener<JSONObject>(this) {
            @Override
            public void onSuccess(JSONObject response) {
            	MyLog.e("发布星秀===="+response.toString());
            	UploadImageFileResponse bean = (UploadImageFileResponse)JSON.parseObject(response.toString(),UploadImageFileResponse.class);
                if (bean != null) {
                	
					//ToastUtil.show(mContext, bean.getBody().getMessage());
					doPostChat(bean.getBody().getResult().getDataList());
				} 
                
            }

            @Override
            public void onError(String code, String message) {
                dismissProgress();
                ToastUtil.show(mContext, message);
            }

            @Override
            public void onCompleted() {
                dismissProgress();
            }
        };
        executeRequest(mContext, new MultipartRequest(url, params, listener, listener));
    }
	

	/**
	 * 发布动态信息
	 */
	private void doPostChat(ArrayList<String> images) {

		if (!AndroidUtil.isNetworkAvailable(this)) {
			ToastUtil.show(mContext,
					getResources().getString(R.string.no_connector));
			return;
		}
		showProgress("", "", true);
		Map<String, String> params = new HashMap<String, String>();
		params.put("userId", mShPreferencesUtil.getUserId());// 用户ID
		params.put("currUserId", mShPreferencesUtil.getUserId());// 当前登陆用户ID
		//String[] tmepImages = (String[])images.toArray();
		params.put("chatImgA", images.toString());// 图片
		
		params.put("chatText", edit_dynamic_desc.getText().toString().trim());// 圈子内容
		params.put("chatPosition", text_location.getText().toString().trim()); // 圈子位置
		if (text_location.getTag() != null) {

			LatLonPoint point = (LatLonPoint) text_location.getTag();
			params.put("chatLongitude", point.getLongitude() + "");// 经度
			params.put("chatLatitude", point.getLatitude() + ""); // 纬度

		}else{
			
			params.put("chatLongitude", mShPreferencesUtil.getLongitude());// 经度
			params.put("chatLatitude", mShPreferencesUtil.getLatitude()); // 纬度
		}
		
		params.put("chatState", 0+"");// 圈子状态(0-有效,1-已删除)
		params.put("chatType",0+"");// 圈子类型(0-图文,1-视频)
		params.put("chatCreatetime",mInitEndTime);// 圈子发布时间

		Map<String, String> lastParams = NetworkUtil
				.generaterPostRequestParams(mContext, params);

		String postUrl = HttpUrlConstant.getPostUrl(this,
				HttpUrlConstant.SAVE_CHAT);
		OnResponseListener<Response> listener = new OnResponseListener<Response>(
				this) {

			@Override
			public void onSuccess(Response response) {

				ToastUtil.show(mContext, response.getBody().getMessage());
				//跳转至我的动态页面
				MyStarDynamicActivity.intoActivity(mContext);
				mContext.finish();
			}

			@Override
			public void onError(String code, String message) {

				ToastUtil.show(mContext, message);
			}

			@Override
			public void onCompleted() {

				dismissProgress();
			}
		};
		executeRequest(new FastJsonRequest<Response>(Request.Method.POST,
				postUrl, Response.class, listener, listener)
				.setParams(lastParams));

	}

	/**
	 * 选择操作图片dialog
	 */
	private void showUploadImageDialog() {

		if (uploadImageDialog == null) {
			uploadImageDialog = new UploadImageDialog(this, R.style.ShareDialog);

			// 相机
			uploadImageDialog
					.setOnTakePhotoClickListener(new View.OnClickListener() {
						@Override
						public void onClick(View v) {
							Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
							startActivityForResult(openCameraIntent, Constants.REQUEST_CODE_TAKE_PHOTO);
							
							/*String filename = String.format("_%1$s.jpg",System.currentTimeMillis());
							cameraFile = new File(FileUtil.getStructureDirs(FileUtil.IMAGE_PATH),filename);
							Intent takeIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
							takeIntent.putExtra(MediaStore.EXTRA_OUTPUT,Uri.fromFile(cameraFile));
							startActivityForResult(takeIntent,REQUEST_CODE_TAKE_PHOTO);*/
						}
					});

			// 本地相册
			uploadImageDialog
					.setOnPickPhotoClickListener(new View.OnClickListener() {
						@Override
						public void onClick(View v) {

							Intent intent = new Intent(mContext,AlbumActivity.class);
							intent.putExtra(Constants.IMAGE_RELEASE_TYPE, Constants.IMAGE_RELEASE_TYPE_DYNAMIC);
							//startActivityForResult(intent,Constants.IMAGE_TYPE_DYNAMIC_REQUEST_CODE);
							startActivity(intent);
							overridePendingTransition(R.anim.activity_translate_in,R.anim.activity_translate_out);

							/*
							 * Intent pickIntent = new
							 * Intent(Intent.ACTION_PICK, null);
							 * pickIntent.setDataAndType
							 * (MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
							 * "image/*"); startActivityForResult(pickIntent,
							 * REQUEST_CODE_PICK_PHOTO);
							 */
						}
					});
		}
		uploadImageDialog.show();
	}

	/**
	 * 上传视频
	 */
	private void showUploadVideoDialog() {

		if (uploadVideoDialog == null) {
			uploadVideoDialog = new UploadVideoDialog(this, R.style.ShareDialog);

			uploadVideoDialog
					.setOnPublishClickListener(new View.OnClickListener() {
						@Override
						public void onClick(View v) {

							ToastUtil.show(mContext, "发布小视频");
						}
					});
			uploadVideoDialog
					.setOnYouKuLinkClickListener(new View.OnClickListener() {
						@Override
						public void onClick(View v) {
							DynamicYouKuLinkActivity.intoActivity(mContext);
							ToastUtil.show(mContext, "发布优酷链接");
						}
					});
		}
		uploadVideoDialog.show();
	}

	/**
	 * 相机拍照获取数据
	 */
	private void handleFromCamera(Intent data) {
		
		
		String fileName = String.valueOf(System.currentTimeMillis());
		Bitmap bm = (Bitmap) data.getExtras().get("data");
		
		cameraFile = new File(FileUtil.getStructureDirs(FileUtil.IMAGE_PATH),fileName);
		ImageItem takePhoto = new ImageItem();
		takePhoto.setBitmap(bm);
		takePhoto.setImagePath(cameraFile.getAbsolutePath());
		Bimp.tempSelectBitmap.add(takePhoto);
		
		/*fileImagePath = cameraFile.getAbsolutePath();
		Bitmap photo = BitmapFactory.decodeFile(fileImagePath);
		image_photo.setImageBitmap(photo);
		String uploadFile = BitmapUtil.compressImage(fileImagePath,
		image_photo.getWidth(), image_photo.getHeight());
		PicassoImageLoaderUtil.loadImage(mContext, uploadFile, image_photo);*/
	}

	/**
	 * 从手机相册获取数据
	 */
	private void handleFromPhotos(Intent data) {
		if (data == null) {
			return;
		}
		Uri selectedImage = data.getData();
		if (selectedImage == null) {
			return;
		}
		Cursor cursor = getContentResolver().query(selectedImage, null, null,
				null, null);
		String picturePath;
		if (cursor != null) {
			cursor.moveToFirst();
			int columnIndex = cursor.getColumnIndex("_data");
			picturePath = cursor.getString(columnIndex);
			cursor.close();
			cursor = null;

			if (picturePath == null || "".equals(picturePath)) {
				return;
			}
		} else {
			File file = new File(selectedImage.getPath());
			if (!file.exists()) {
				return;
			}
			picturePath = file.getAbsolutePath();
		}
		fileImagePath = picturePath;
		Bitmap photo = BitmapFactory.decodeFile(fileImagePath);
		image_photo.setImageBitmap(photo);
		// String uploadFile = BitmapUtil.compressImage(picturePath,
		// image_photo.getWidth(), image_photo.getHeight());
		// PicassoImageLoaderUtil.loadImage(mContext, fileImagePath,
		// image_photo);
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == Activity.RESULT_OK) {
			switch (requestCode) {
			case Constants.REQUEST_CODE_TAKE_PHOTO:
				if (Bimp.tempSelectBitmap.size() < 9) {
					
					handleFromCamera(data);
				}
				
				break;
			case Constants.REQUEST_CODE_PICK_PHOTO:
				handleFromPhotos(data);
				break;
			case Constants.ANNUNCIATE_LOCATION_REQUEST_CODE:
				PoiItem poiItem = data
						.getParcelableExtra(Constants.ANNUNCIATE_LOCATION_EXTRA_NAME);
				setLocationInfo(poiItem);
				break;
			default:
				break;
			}
		}
	}

	private void setLocationInfo(PoiItem poi) {

		text_location.setText(poi.getCityName() + poi.getAdName()
				+ poi.getSnippet() + "(" + poi.getTitle() + ")");
		// 经纬度
		text_location.setTag(poi.getLatLonPoint());
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			onBack();
		}
		return true;
	}

	private void onBack() {

		for (int i = 0; i < PublicWay.activityList.size(); i++) {
			if (null != PublicWay.activityList.get(i)) {
				PublicWay.activityList.get(i).finish();
			}
		}

	}
	
	@Override
	protected void onRestart() {
		adapter.notifyDataSetChanged();
		super.onRestart();
	}
}
